package com.gz.logistics.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.pdf.PdfDocument;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.logistics.R;
import com.gz.logistics.adapter.HomeOrderAdapter;
import com.gz.logistics.adapter.OutingAssembleAdapter;
import com.gz.logistics.adapter.QueryOrderAdapter;
import com.gz.logistics.adapter.SpinnerAdapter;
import com.gz.logistics.app.Define;
import com.gz.logistics.app.OrderDetailActivity;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.BaseListener;
import com.gz.logistics.library.listener.GetPartsListener;
import com.gz.logistics.library.listener.GetQueryorderListener;
import com.gz.logistics.library.listener.HomeOrderListener;
import com.gz.logistics.library.listener.RequestCode;
import com.gz.logistics.library.pojo.CustomerSpinnerObject;
import com.gz.logistics.library.pojo.OrderInfo;
import com.gz.logistics.library.pojo.OrderStatusInfo;
import com.gz.logistics.library.pojo.PartInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.pojo.WillOutStorageAassemble;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.CrashHandler;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.FooterView;
import com.gz.logistics.widget.LoadingCover;
import com.gz.logistics.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class QureyOrderFragment extends Fragment implements View.OnClickListener,
        AdapterView.OnItemClickListener,
        PullToRefreshBase.OnRefreshListener,
        LoadingCover.OnLoadingCoverRefreshListener, FooterView.OnFooterViewRefreshListener {
    private String TAG = QureyOrderFragment.class.getSimpleName();
    private List<OrderInfo> mDataList;
    private QueryOrderAdapter mAdapter; private PullToRefreshListView mPullList;
    private LoadingCover mLoadingCover;
    private View mConvertView;
    private Context mContext;
    private UserInfo userInfo;
    private FooterView mFooterView;
    private Dialog mLoadingData;
    private MyGetQueryorderListener pullRequestListener;
    private MyGetQueryorderListener scrollRequestListener;
    private MyGetPartsListener myGetPartsListener;

    private SpinnerAdapter partSpinnerAdapter;
    private SpinnerAdapter statusSpinnerAdapter;
    private MyPartSpinnerOnItemSelectListener mPartSpinnerListener;
    private MyStatusSpinnerOnItemSelectListener mStatusSpinnerListener;
    private SpinerPopWindow mPartSpinnerPopWindow;
    private SpinerPopWindow mStatusSpinnerPopWindow;
    private List<CustomerSpinnerObject> statusList ;//订单状态列表
    private List<CustomerSpinnerObject> partList;// 片区列表

    private MyHandler mHandler;

    private TextView iv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private RelativeLayout rl_choice_for_part;
    private RelativeLayout rl_choice_for_status;
    private RelativeLayout rl_choice_for_order;

    private TextView tv_part_name;
    private TextView tv_status;
    private TextView tv_order;

    private int page = 1;
    private int selectedPartId = -1; // 当前选中的片区ID
    private int Selectedstatus = Define.ORDER_STATUS_ALL;// 当前选中的订单状态，默认为“全部订单”
    private int orderType = -1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mConvertView == null){
            mConvertView = inflater.inflate(R.layout.fragment_qurey_order,container,false);
            init(inflater);
        }

        initAdapter();
        mHandler = new MyHandler(this);
        initListener();
        ininDate();
        onLoadingCoverRefresh();
        return mConvertView;
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        pullRequestListener.release();
        scrollRequestListener.release();
        mHandler.release();
        myGetPartsListener.release();
        mPartSpinnerListener.release();
        mStatusSpinnerListener.release();
    }
    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 片区选择 和 状态选择 button 点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_choice_for_part:
                if(partList.size() <= 0 ){
                    ToastUtils.showToast(getActivity(),"片区列表为空");
                    return ;
                }
                mPartSpinnerPopWindow.setWidth(rl_choice_for_part.getWidth()*2);
                mPartSpinnerPopWindow.showAsDropDown(rl_choice_for_part);
                break;
            case R.id.rl_choice_for_status:
                if(statusList.size() <= 0 ){
                    ToastUtils.showToast(getActivity(),"状态列表为空");
                    return ;
                }
                mStatusSpinnerPopWindow.setWidth(rl_choice_for_status.getWidth());
                mStatusSpinnerPopWindow.showAsDropDown(rl_choice_for_status);
                break;

        }

    }

    /**
     * 订单列表 listView 点击事件
     * @param adapterView
     * @param view
     * @param i
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (l < 0){
            return ;
        }
        OrderInfo clickItem = mDataList.get((int)l);
        if (clickItem != null){
            Intent intent = new Intent();
            intent.setClass(mContext, OrderDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("clickOrder",clickItem);
            intent.putExtras(bundle);
            startActivityForResult(intent, Define.ACTIVITY_CODE_ORDER_DETAIL);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Define.ACTIVITY_CODE_ORDER_DETAIL && resultCode == Define.ACTIVITY_CODE_ORDER_DETAI_CHANGE){
            if (data != null){ // 如果订单详情界面做了修改，刷新界面（不请求服务器），否则什么也不做
                String changedSn = data.getStringExtra("changedOrderSn");
                onLoadingCoverRefresh();
            }
        }

    }

    @Override
    public void onLoadingCoverRefresh() {
        page = 1;
        selectedPartId = -1;
        Selectedstatus = Define.ORDER_STATUS_ALL;
        loadData(selectedPartId,Selectedstatus,page,pullRequestListener);

    }

    /**
     * 下拉刷新
     * @param refreshView
     */
    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        page = 1;
        selectedPartId = -1;
        Selectedstatus = Define.ORDER_STATUS_ALL;
        loadData(selectedPartId, Selectedstatus, page, pullRequestListener);

    }

    /**
     * 加载更多
     */
    @Override
    public void onFooterViewRefresh() {
        page++;
        loadData(selectedPartId, Selectedstatus, page, scrollRequestListener);

    }

    public void initAdapter() {
        mDataList = new ArrayList<OrderInfo>();
        mAdapter = new QueryOrderAdapter(mDataList,mContext);
        mPullList.setAdapter(mAdapter);

        // 初始化"片区选择" 控件
        partList = new ArrayList<CustomerSpinnerObject>();
        partSpinnerAdapter = new SpinnerAdapter(this.getActivity(),partList);
        mPartSpinnerPopWindow = new SpinerPopWindow(this.getActivity());
        mPartSpinnerPopWindow.setAdatper(partSpinnerAdapter);


        statusList = new ArrayList<CustomerSpinnerObject>();
        statusSpinnerAdapter = new SpinnerAdapter(this.getActivity(),statusList);
        mStatusSpinnerPopWindow = new SpinerPopWindow(this.getActivity());
        mStatusSpinnerPopWindow.setAdatper(statusSpinnerAdapter);

    }

    /**
     * 初始化控件
     * @param mInflater
     */
    private void init(LayoutInflater mInflater) {
        mContext = getActivity().getApplicationContext();
        userInfo = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));

        mPullList = (PullToRefreshListView) mConvertView.findViewById(R.id.list);
        iv_actionbar_title = (TextView) mConvertView.findViewById(R.id.iv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) mConvertView.findViewById(R.id.tv_actionbar_deliveryName);


        rl_choice_for_part = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_part);
        rl_choice_for_status = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_status);
        rl_choice_for_order = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_order);

        tv_part_name = (TextView) mConvertView.findViewById(R.id.tv_part_name);
        tv_status = (TextView) mConvertView.findViewById(R.id.tv_time);
        tv_order = (TextView) mConvertView.findViewById(R.id.tv_order);
        mLoadingCover = (com.gz.logistics.widget.LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);

        mFooterView = (FooterView) mInflater.inflate(R.layout.footer_view, null);
        mPullList.getRefreshableView().addFooterView(mFooterView);

        mLoadingData = new Dialog(getActivity(),R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);
    }

    /**
     * 初始化数据
     */
    private void ininDate() {
        iv_actionbar_title.setText("订单查询");
        tv_actionbar_deliveryName.setText("配送员：" + userInfo.getUser_name());
        OrderStatusInfo statusInfo = null;
        for(int i = 0 ; i < 5 ;i++){
            statusInfo = new OrderStatusInfo();
            if (i == 0 ){

                statusInfo.setStatus_id(Define.ORDER_STATUS_ALL);
                statusInfo.setStatus_name("所有");
            }else if (i == 1 ){

                statusInfo.setStatus_id(Define.ORDER_STATUS_LOGISTIC_SIGNED);
                statusInfo.setStatus_name("物流已签收");
            }else if (i == 2 ){

                statusInfo.setStatus_id(Define.ORDER_STATUS_LOGISTIC_NOT_SIGN);
                statusInfo.setStatus_name("物流待签收");
            }else if (i == 3 ){

                statusInfo.setStatus_id(Define.ORDER_STATUS_DELIVERY_SIGNED);
                statusInfo.setStatus_name("业务已签收");
            }else if (i == 4 ){

                statusInfo.setStatus_id(Define.ORDER_STATUS_DELIVERY_NOT_SIGN);
                statusInfo.setStatus_name("业务待签收");
            }
            statusList.add(statusInfo);

        }
        //statusSpinnerAdapter.notifyDataSetChanged();

    }

    /**
     * 初始化各种监听器
     */
    private void initListener() {

        mPullList.setOnRefreshListener(this);
        mPullList.setOnItemClickListener(this);
        mPullList.setOnScrollListener(mFooterView);

        mFooterView.setOnFooterViewRefreshListener(this);

        mLoadingCover.setOnLoadingCoverRefreshListener(this);
        pullRequestListener = new MyGetQueryorderListener(this, RequestCode.PULL);
        scrollRequestListener = new MyGetQueryorderListener(this,RequestCode.SCROLL);
        myGetPartsListener = new MyGetPartsListener(this);

        rl_choice_for_part.setOnClickListener(this);
        rl_choice_for_status.setOnClickListener(this);
        rl_choice_for_order.setOnClickListener(this);

        mPartSpinnerListener = new MyPartSpinnerOnItemSelectListener(this);
        mStatusSpinnerListener = new MyStatusSpinnerOnItemSelectListener(this);

        mPartSpinnerPopWindow.setItemListener(mPartSpinnerListener);
        mStatusSpinnerPopWindow.setItemListener(mStatusSpinnerListener);
    }

    /**
     * 从服务器加载数据
     * @param selectedPartId
     * @param selectedstatus
     * @param page
     * @param listener
     */
    public void loadData(int selectedPartId ,int selectedstatus,int page,BaseListener listener){

               if (selectedstatus == Define.ORDER_STATUS_ALL){
                   //所有订单
                   IOrder.getInstance().getQueryOrder(Define.FLAG_TRANS_STATUS_ALL,Define.FLAG_DELEVERY_STATUS_ALL,
                           selectedPartId,page,listener);

               }else if (selectedstatus == Define.ORDER_STATUS_LOGISTIC_SIGNED){
                   //物流已签收
                   IOrder.getInstance().getQueryOrder(Define.FLAG_TRANS_STATUS_SIGNED,Define.FLAG_DELEVERY_STATUS_ALL,
                           selectedPartId,page,listener);

               }else if (selectedstatus == Define.ORDER_STATUS_LOGISTIC_NOT_SIGN){
                   //物流待签收
                   IOrder.getInstance().getQueryOrder(Define.FLAG_TRANS_STATUS_NO_SIGN,Define.FLAG_DELEVERY_STATUS_ALL,
                           selectedPartId,page,listener);

               }else if (selectedstatus == Define.ORDER_STATUS_DELIVERY_SIGNED){
                   // 业务已签收
                   IOrder.getInstance().getQueryOrder(Define.ORDER_STATUS_LOGISTIC_SIGNED,Define.FLAG_DELEVERY_STATUS_SIGNED,
                           selectedPartId,page,listener);

               }else if (selectedstatus == Define.ORDER_STATUS_DELIVERY_NOT_SIGN){
                   //业务代签收
                   IOrder.getInstance().getQueryOrder(Define.ORDER_STATUS_LOGISTIC_SIGNED,Define.FLAG_DELEVERY_STATUS_NO_SIGN,
                           selectedPartId,page,listener);
               }

    }



    /**
     * 首页订单加载回调接口
     */
    private static class  MyGetQueryorderListener extends GetQueryorderListener {
        private QureyOrderFragment mOuter;

        public MyGetQueryorderListener(QureyOrderFragment mOuter,RequestCode code) {

            super(code);
            this.mOuter = mOuter;


        }
        public void release(){
            new WeakReference<QureyOrderFragment>(mOuter);
        }
        @Override
        public void onNoNetWork() {
            if (mOuter.mPullList.isRefreshing()){
                mOuter.mPullList.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.mFooterView.onRefreshFailed();
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
            ToastUtils.showToast(mOuter.getActivity(), Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingCover.onRefreshFailed();
            mOuter.mFooterView.onRefreshFailed();
            if (mOuter.mPullList.isRefreshing()){
                mOuter.mPullList.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }

            ToastUtils.showToast(mOuter.getActivity(),"加载失败");

        }

        @Override
        public void onResponseSuccess(List<OrderInfo> orderInfoList) {

            if (getRequestCode() == RequestCode.PULL){
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
            }
            mOuter.mDataList.addAll(orderInfoList);
            mOuter.mAdapter.notifyDataSetChanged();

            if (orderInfoList.size() < Define.LISTVIEW_ITEM_MIN_SIZE){
                mOuter.mFooterView.onRefreshComplete();
                mOuter.mPullList.setOnScrollListener(null);
            }else{
                mOuter.mFooterView.onRefreshSuccess();
                mOuter.mPullList.setOnScrollListener(mOuter.mFooterView);
            }

            mOuter.mLoadingCover.onRefreshSuccess();
            if ( mOuter.mPullList.isRefreshing()) {
                mOuter.mPullList.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }


            // 通知主线程开一个子线程去从服务器获取片区列表
            mOuter.mHandler.sendEmptyMessage(1);


        }

        @Override
        public void onNoDistribute() {
            mOuter.mDataList.clear();
            mOuter.mAdapter.notifyDataSetChanged();

            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullList.setOnScrollListener(null);

            mOuter.mLoadingCover.onRefreshSuccess();
            if (mOuter.mPullList.isRefreshing()) {
                mOuter.mPullList.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), "还未分配到派送订单");
        }

        @Override
        public void onNoConditionSatisfiedOrder() {
            mOuter.mDataList.clear();
            mOuter.mAdapter.notifyDataSetChanged();

            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullList.setOnScrollListener(null);

            mOuter.mLoadingCover.onRefreshSuccess();

            if (mOuter.mPullList.isRefreshing()) {
                mOuter.mPullList.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), "没有满足条件的订单");
        }

        @Override
        public void onDataError() {
            mOuter.mDataList.clear();
            mOuter.mAdapter.notifyDataSetChanged();

            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullList.setOnScrollListener(null);

            mOuter.mLoadingCover.onRefreshSuccess();

            if (mOuter.mPullList.isRefreshing()) {
                mOuter.mPullList.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }

            ToastUtils.showToast(mOuter.getActivity(),"数据异常");

        }

    }
    /**
     * 获取片区的监听器
     */
    public static  class MyGetPartsListener extends GetPartsListener {
        private QureyOrderFragment mOuter;

        public MyGetPartsListener(QureyOrderFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<QureyOrderFragment>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<PartInfo> partInfos) {
            CrashHandler.i("MyGetPartsListener", "partInfos的大小=" + partInfos.size());
            PartInfo ignorePart = new PartInfo();
            ignorePart.setPart_id(-1);
            ignorePart.setIsSelected(false);
            ignorePart.setPart_name("全部");
            partInfos.add(0, ignorePart);

            mOuter.partList.clear();
            mOuter.partList.addAll(partInfos);
            mOuter.mHandler.sendEmptyMessage(2);


        }
        @Override
        public void onPartIsEmpty() {

        }
        @Override
        public void onResponseFailed() {

        }
    }



    public static class MyHandler extends android.os.Handler{
        private QureyOrderFragment mOuter;

        public MyHandler(QureyOrderFragment mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<QureyOrderFragment>(mOuter);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    IOrder.getInstance().getParts(mOuter.myGetPartsListener);
                    break;
                case 2:
                    mOuter.mPartSpinnerPopWindow.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     *片区下拉列表的 item 点击事件监听器
     */
    public static class MyPartSpinnerOnItemSelectListener implements SpinerPopWindow.ISpinnerOnItemSelectListener {
        private QureyOrderFragment mOuter;

        public MyPartSpinnerOnItemSelectListener(QureyOrderFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<QureyOrderFragment>(mOuter);
        }
        @Override
        public void onSpinnerItemClick(int position) {
            mOuter.mLoadingData.show();
            mOuter.page = 1;
            mOuter.selectedPartId = ((PartInfo)mOuter.partList.get(position)).getPart_id();
            mOuter.Selectedstatus = Define.ORDER_STATUS_ALL;  // 恢复 订单状态 为全部订单
            mOuter.loadData(mOuter.selectedPartId,mOuter.Selectedstatus,mOuter.page,mOuter.pullRequestListener);


        }
    }

    /**
     * 状态下拉列表 item 点击事件 监听器
     */
    public static class MyStatusSpinnerOnItemSelectListener implements SpinerPopWindow.ISpinnerOnItemSelectListener {
        private QureyOrderFragment mOuter;

        public MyStatusSpinnerOnItemSelectListener(QureyOrderFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<QureyOrderFragment>(mOuter);
        }
        @Override
        public void onSpinnerItemClick(int position) {
            mOuter.mLoadingData.show();
            mOuter.page = 1;
            mOuter.selectedPartId = -1;
            mOuter.Selectedstatus = ((OrderStatusInfo)mOuter.statusList.get(position)).getStatus_id();
            mOuter.loadData(mOuter.selectedPartId,mOuter.Selectedstatus,mOuter.page,mOuter.pullRequestListener);


        }
    }




}
